# _*_ coding:utf-8 _*_
# @Time  : 2023.05.31
# @Author: zizlee
import json
import time

import requests
import pandas as pd
from urllib3 import disable_warnings
disable_warnings()


def get_variety_en():
    vdf = pd.read_csv('variety.csv')
    v_list = []
    for i in vdf.to_dict(orient='records'):
        v_list.append({
            'NAME': i['NAME'].split(':')[1],
            'VARIETY': i['VARIETY'],
            'THS_CODE': i['THS_CODE']
        })
    return v_list


def add_indexes(start_id=0):
    records = []
    with open('ir.json', 'r', encoding='utf8') as f:
        records = json.load(f)
    records.reverse()
    for i, row in enumerate(records, 1):
        if is_exist(index=row['source_id'], plat=row['source_plat']):
            print(f'存在{row["id"]}', row)
            continue
        # row['source_plat'] = 'ruizhi'
        # row['source_id'] = ''

        url = "http://210.13.218.130:9001/v1/admin/dataindex/create/"
        r = requests.post(url, json={
            'name': row['name_zh'],
            'frequency': row['frequency'],
            'unit': row['unit'],
            'start_date': row['startdate'],
            'plat': row['source_plat'],
            'plat_id': row['source_id'],
            'source': row['raw_source'],
            'note': ''
        }, verify=False)
        time.sleep(1)
        # print(r.json())
        t = 'THS指标' if row['source_plat'] == 'ths' else 'WIND指标'
        # t = '自己系统'
        str_i = '%06d' % (start_id + i)
        print(f'{str_i},1,{t},,{row["frequency"]},{row["source_id"]},,,,{row["variety"]},{row["id"]},,{row["name_zh"]}')


def get_indexes(start_id=1):
    url = "http://210.13.218.130:9001/v1/admin/dataindex/retrieve/?kw=&page=1&page_size=400"
    r = requests.get(url, verify=False)
    indexes = r.json()['data']['data']['rows']
    indexes = list(filter(lambda x: x['id'] >= start_id, indexes))
    indexes.reverse()

    v_list = get_variety_en()
    v_dict = {i['NAME']: i['VARIETY'] for i in v_list}
    ths_dict = {i['NAME']: i['THS_CODE'] for i in v_list}

    for i, row in enumerate(indexes, 0):
        # 596,THS指标,,月,M004088099,,,,,,创业板综合指数
        index_id = '%06d' % row['id']
        index_plat = 'WIND指标' if len(row["plat_id"]) == 8 else 'THS指标'
        index_plat = '自己系统'
        # 000001, 1, 历史行情, close, 日,, IF, IFZL.CFE,, , , 主力收盘价: 沪深300
        # 008297, 1,THS指标,,日,R00000008297,,,,,,主力成交量:合成橡胶
        print(f'{index_id},1,{index_plat},,{row["frequency"]},{row["plat_id"]},,,,,,,{row["name"]}')

        name = row['name'].split(':')[1]
        # print(f'{index_id},1,历史行情,openInterest,日,,{v_dict.get(name)},{ths_dict.get(name)},,,,{row["name"]}')


def is_exist(index, plat):
    url = 'http://210.13.218.130:9001/v1/admin/dataindex/exist/?plat={}&plat_id={}'.format(plat, index)
    r = requests.get(url, verify=False)
    return r.json()['data']['exist']


if __name__ == '__main__':
    add_indexes(start_id=9123)
    # get_indexes(start_id=9033)






